﻿using System.IO;
using CRM.Authorization.Permissions;
using CRM.Authorization.Rule;
using CRM.Extensions;
using CRM.Services;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace CRM.Controllers.SystemManage
{
    [Route("/api/[controller]/[action]")]
    public class SystemController : BaseController
    {
        private readonly IOptionsSnapshot<GlobalSearchService.FakeRatioOptions> _options;
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly ILogger<SystemController> _logger;

        public SystemController(IOptionsSnapshot<GlobalSearchService.FakeRatioOptions> options, IWebHostEnvironment hostEnvironment, ILogger<SystemController> logger)
        {
            _options = options;
            _hostEnvironment = hostEnvironment;
            _logger = logger;
        }

        [HttpGet]
        [Permission(SystemManager.System)]
        public ResultStruct GetConfig()
        {
            _logger.LogInformation("读取数据倍率： {Ratio}", _options.Value.FakeRatio);
            return Success(new
            {
                FakeRatio = _options.Value.FakeRatio
            });
        }
        
        [HttpPost]
        [Permission(SystemManager.System)]
        public ResultStruct EditConfig(JObject input)
        {
            var configPath = Path.Combine(_hostEnvironment.ContentRootPath, "app.json");
            
            var json = configPath.FileToJson();
            json.Merge(input);
            
            json.WriteTo(configPath);
            _logger.LogInformation("写入数据倍率： {Ratio}", input["fakeRatio"].ToString());
            return Success();
        }
    }
}